package cn.ilikes.tools.hbase.jpa.metadatas.orms.pasers;

import java.io.IOException;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;

import cn.ilikes.tools.hbase.jpa.metadatas.orms.elements.EntityMappings;
import cn.ilikes.tools.hbase.jpa.metadatas.orms.elements.NamedQuery;
import cn.ilikes.tools.logs.Loggerfactory;

public class DOM4JPaser {

	private static Logger logger = Loggerfactory.instance(DOM4JPaser.class);

	public void paser(String file, EntityMappings orm) throws DOM4JPaserException {
		Enumeration<URL> xmls = null;
		try {
			xmls = Thread.currentThread().getContextClassLoader().getResources(file);
			if (xmls == null || !xmls.hasMoreElements()) {

				throw new DOM4JPaserException("Could not find any file : " + file);
			}

			while (xmls.hasMoreElements()) {
				paser(xmls.nextElement(), orm);
			}

		} catch (IOException ioex) {
			throw new DOM4JPaserException("Could not find any file : " + file, ioex);
		}

	}

	private void paser(URL url, EntityMappings orm) {
		InputStream is = null;
		try {
			URLConnection conn = url.openConnection();
			conn.setUseCaches(false); // avoid JAR locking on Windows and Tomcat
			is = conn.getInputStream();
			SAXReader saxReader = new SAXReader();
			try {
				Document doc = saxReader.read(is);
				Element root = doc.getRootElement();
				for (Iterator<Element> iter = root.elementIterator(); iter.hasNext();) {
					Element element = iter.next();
					String name = element.getName();
					if (name.equals("named-query")) {
						paserNameQuery(element, orm);
					}

					if (name.equals("package")) {

					}

				}
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {

		} finally {
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
				}
		}
	}

	private void paserNameQuery(Element element, EntityMappings orm) {

		String nameQueryName = element.attributeValue("name");

		NamedQuery namedQuery = new NamedQuery(nameQueryName);
		for (Iterator<Element> iter = element.elementIterator(); iter.hasNext();) {
			Element element_ = iter.next();
			String name = element_.getName();
			if (name.equals("lock-mode")) {
				namedQuery.setLockMode(element_.getText());
			}

			if (name.equals("query")) {
				namedQuery.setQuery(element_.getText());
			}

		}
		orm.getNamedQuerys().put(nameQueryName, namedQuery);
		Loggerfactory.info(logger, "query type name query ; name " + nameQueryName + " query : " + namedQuery.getQuery());
	}
}
